import { render } from "preact";
import { signal, effect } from "@preact/signals";
import App from "./App";
import { initHistory } from "./histories";
import { initEngines } from "./engines";
import { initSettings, changeDark, inner, box as daisyBody } from "./settings";
import { initPresets } from "./presets";
import { initNotes } from "./Widgets/notes";
import { logo, boxes } from "./signals";
import { getLogo, getFavos } from "./Vendor";
import daisy from "../check.css?inline";

initHistory();
initEngines();
initSettings();
initPresets();
initNotes();

const shadow = daisyBody.attachShadow({ mode: "closed" });
const style = document.createElement("style");
style.textContent = daisy;
shadow.append(style);
shadow.append(inner);

const root = document.documentElement;
const oldBody = document.body;
const bodySignal = signal(false);
let isStart = true;

effect(() => {
  oldBody.style.opacity = 0;
  daisyBody.style.opacity = 0;
  if (bodySignal.value) {
    if (isStart) {
      oldBody.remove();
      root.append(daisyBody);
      isStart = false;
    } else {
      setTimeout(() => {
        oldBody.remove();
        root.append(daisyBody);
        daisyBody.style.opacity = 1;
      }, 250);
    }
  } else {
    if (!isStart) {
      setTimeout(() => {
        daisyBody.remove();
        root.append(oldBody);
        oldBody.style.opacity = 1;
      }, 250);
    }
  }
  if (!isStart) {
    globalThis.vendorSugSwitch?.(!bodySignal.value);
  }
});

globalThis.daisyMagic = () => {
  bodySignal.value = !bodySignal.value;
};

window.addEventListener("load", async () => {
  const dark = globalThis.matchMedia("(prefers-color-scheme: dark)");
  logo.value = await getLogo();
  boxes.value = getFavos();
  changeDark(dark.matches);
  dark.addEventListener("change", (event) => {
    changeDark(event.matches);
  });
  bodySignal.value = true;
  render(<App />, inner);
});
